|
1->2->3->4->5->NULL | ListNode *slow = head, *fast = head;
^ ^ | while (k--) {
slow fast ---> | if (fast == NULL) fast = head; // [1]
|_____| | fast = fast->next;
k | }
| if (fast == NULL) return head;
1->2->3->4->5->NULL | while (fast->next) {
^ ^ ^ | fast = fast->next;
head slow fast | slow = slow->next;
|_____| | }
k | List *new_head = slow->next;
| slow->next = NULL;
| fast->next = head;
| return new_head;ΨһҪעÒâµÄÔÚÓÚ:
ÓÃʾÀýÀ´±íʾµ½µ×ʲô½Ð rotate the list to the right by
k places.
| k | origin | after |
|---|---|---|
| 1 | 0->1->2 | 2->0->1 |
| 2 | 0->1->2 | 1->2->0 |
| 3 | 0->1->2 | 0->1->2 |
| 4 | 0->1->2 | 2->0->1 |
¿ÉÒÔ¹Û²ìµÄ³öÀ´£¬µ± k > n
µÄʱºò£¬k = k % n.
²Î¿¼×ÊÁÏ£ºwhat to do when k is greater than size of list ?
#include <cstddef>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (head == NULL || k == 0) return head;
ListNode *slow = head, *fast = head;
while (k--) {
if (fast == NULL) fast = head;
fast = fast->next;
}
if (fast == NULL) return head;
while (fast->next) {
fast = fast->next;
slow = slow->next;
}
ListNode *new_head = slow->next;
slow->next = NULL;
fast->next = head;
return new_head;
}
};